#include "../include/initMouse.h"
#include "../include/mouse.h"
#include "../include/video.h"
#include "../include/protpant.h"

static int copybuffcant;
char xMove,yMove, mouseMove;
static int contd = 0,contu = 0,contr = 0,contl = 0, sens = 3;
extern EOI();
extern inportb(int a);
extern outportb(int a, int b);
static char copybuff[4000];
static int leftpressed = 0, rightpressed = 0;
static vid backup[NCOL*NROW];
void readyToRead(void){
  
int flag;
  int time = 10000;
  while( time-- > 0) {
  flag = inportb(0x64);
  if((flag & 0x21) == 0x21)
	return;
     }
}

void Adjustmouse(int i)
{
	sens= i + 1;
	contd = 0;
	contu = 0;	
	contr = 0;
	contl = 0; 
}

void
getPacket(void){
readyToRead();
mouseMove = inportb(0x60);
EOI();
readyToRead();
xMove = inportb(0x60);
EOI();
readyToRead();
yMove = inportb(0x60);
EOI();
}


void
mouse_handler(void){	
	int i;
	_Cli();
	getPacket();
	protpantdisable();
	if((mouseMove & 0x08) != 0x08)
		return;
	for(i = 0; i < yMove || i < getY() || i < 25; i+=25){
	
			if((( mouseMove & 0x20) == 0x20) && ((mouseMove & 0x40) != 0x40))
				if (contd % (sens *3) == 0)
				{
				mousedown();
				contd++;
				}
				else
				contd++;
			else
				if (contu % (sens *3) == 0)
				{
				mouseup();
				contu++;
				}
				else
				contu++;
	}
for( i = 0; i < xMove || i < getX() || i < 80 ; i+=80){

if(((mouseMove & 0x10) == 0x10) && ((mouseMove & 0x80) != 0x80))
				if (contl % (sens) == 0)
				{
				mouseleft();
				contl++;
				}
				else
				contl++;
			else
				if (contr % (sens  ) == 0)
				{
				mouseright();
				contr++;
				}
				else
				contr++;
}

if( (mouseMove & 0x01) == 0x01){
if( leftpressed == 0)
{
leftpressed = 1;
initVideoCopy(backup);
/*
print("aprete el click izquierdo");*/
}
}
else
{
if (leftpressed == 1)
{
copybuffcant = endVideoCopy(copybuff);
}
/*print("acabo de soltar");*/
leftpressed = 0;
}
if((mouseMove & 0x02) == 0x02){
if( rightpressed == 0)
{
rightpressed = 1;

fmtprint(copybuff, copybuffcant);

/*print("es el click derecho");*/
}
}
else
{
if (rightpressed == 1)
{
}
/*print("acabo de soltar");*/
rightpressed = 0;
}

_Sti();


}
